package ks.packs.anotherDay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

public class jerichoParser {

	String BusNum;

	jerichoParser() {
	}

	jerichoParser(String pBusNum) {
		BusNum = pBusNum;
	}

	public String parseMP3(InputStream data) {

		try {
			Source source = new Source(data);

			source.fullSequentialParse();

			List<Element> list = source.getAllElements();

			for (Element e : list) {

				String text = e.toString();

				if (text.indexOf("mp3") > 0 && e.getDepth() >= 3) {
					LinkGetter lg = new LinkGetter(null);
					List<String> al = lg.getLinks(text);

					String url = al.toString();

					return url;
				}

			}

		} catch (Exception e) {

		}

		return null;
	}

	public class LinkGetter {
		private Pattern htmltag;
		private Pattern link;
		private final String root;

		public LinkGetter(String root) {
			this.root = root;
			htmltag = Pattern.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>");
			link = Pattern.compile("href=\"[^>]*\">");

		}

		public List<String> getLinks(String Content) {
			List<String> links = new ArrayList<String>();
			try {

				Matcher tagmatch = htmltag.matcher(Content);
				while (tagmatch.find()) {
					Matcher matcher = link.matcher(tagmatch.group());
					matcher.find();
					String link = matcher.group().replaceFirst("href=\"", "")
							.replaceFirst("\">", "");

					if (valid(link)) {
						links.add(link);
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return links;
		}

		private boolean valid(String s) {
			if (s.matches("javascript:.*|mailto:.*")) {
				return false;
			}
			return true;
		}

		private String makeAbsolute(String url, String link) {
			if (link.matches("http://.*")) {
				return link;
			}
			if (link.matches("/.*") && url.matches(".*$[^/]")) {
				return url + "/" + link;
			}
			if (link.matches("[^/].*") && url.matches(".*[^/]")) {
				return url + "/" + link;
			}
			if (link.matches("/.*") && url.matches(".*[/]")) {
				return url + link;
			}
			if (link.matches("/.*") && url.matches(".*[^/]")) {
				return url + link;
			}
			throw new RuntimeException("Cannot make the link absolute. Url: "
					+ url + " Link " + link);
		}
	}

}
